// src/store/authStore.ts
import Cookies from 'js-cookie';
import { defineStore } from 'pinia';
import { ref } from 'vue';
import { refreshToken as refreshTokenApi } from '@/api/login/userLogin';

export const useAuthStore = defineStore('auth', () => {
  const accessToken = ref<string | null>(null);
  const refreshToken = ref<string | null>(null);
  const intervalId = ref<any | null>(null);

  // 初始化函数，从 cookies 中获取 token
  const initialize = () => {
    const token1 = Cookies.get('access_token_lf');
    const token2 = Cookies.get('refresh_token_lf')
    if (token1 && token2) {
      accessToken.value = token1;
      refreshToken.value = token2
    }
  };

  // 设置 access token，并存储在 cookies 中
  const setAccessToken = (token: string) => {
    accessToken.value = token;
    Cookies.set('access_token_lf', token);
  };

  // 设置refresh token
  const setRefreshToken = (token: string) => {
    refreshToken.value = token
    Cookies.set('refresh_token_lf', token)
  }

  // 清除 access token，并从 cookies 中移除
  const clearAccessToken = () => {
    accessToken.value = null;
    Cookies.remove('access_token_lf');
  };

  const clearRefreshToken = () => {
    refreshToken.value = null
    Cookies.remove('refresh_token_lf');
  };

  // 关闭定时器
  const stopTokenRefreshTask = () => {
    if (intervalId.value) {
      clearInterval(intervalId.value);
      intervalId.value = null;
    }
  }
  // 启动定时刷新token函数
  const startTokenRefreshTask = () => {
    // 防止多次启动定时器
    if (intervalId.value)
      return
    intervalId.value = setInterval(async () => {
      refreshTokenApi().then((responseToken) => {
      // 设置Cookie
        setAccessToken(responseToken.access_token);
        setRefreshToken(responseToken.refresh_token);
      }).catch(() => {
        clearAccessToken();
        clearRefreshToken();
      })
    }, 20 * 60 * 1000) // 每 20 分钟刷新一次 token
  };

  return {
    accessToken,
    refreshToken,
    setAccessToken,
    clearAccessToken,
    setRefreshToken,
    clearRefreshToken,
    startTokenRefreshTask,
    stopTokenRefreshTask,
    initialize,
  };
});
